//
//  LocalNSData.m
//  DolphinMusic
//
//  Created by dlios on 15-3-25.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "LocalNSData.h"
#import "AFHTTPRequestOperation.h"
@implementation LocalNSData

+ (void)getRequstUrl:(NSString *)str completion:(void (^)(NSData *))block
{
    NSString *urlStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *requst = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    requst.HTTPMethod = @"GET";
    
    // 拼接数据存储的地址
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    // 文件路径
    NSString *path = [NSString stringWithFormat:@"%@/%d.mp3",docPath,[str hash]];
    NSLog(@"文件路径:%@", path);
    AFHTTPRequestOperation *opretion = [[AFHTTPRequestOperation alloc] initWithRequest:requst];
    
    [opretion setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = opretion.responseString;
        NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
        
        BOOL result = [NSKeyedArchiver archiveRootObject:data toFile:path];
        //            NSLog(@"存储:%d", result);
        block(data);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 从本地读取数据
        NSData *data1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if (data1 != nil) {
            //            NSLog(@"使用本地存储的数据");
            block(data1);
        }else
        {
            //            NSLog(@"本地无可用的数据");
        }
        
    }];
    // 队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:opretion];
}

@end
